package com.ease.model.criterion;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ease.common.vo.Entry;

/**
 * 
 * @author nathanleewei
 * 
 */
public class Junction extends CriterionSupport implements Criterion {

	/**
	 *
	 */
	private static final long serialVersionUID = -2499984304851253268L;

	private List<Criterion> criteria = new ArrayList<Criterion>();

	private String op;

	public Junction() {

	}

	public void setOp(String op) {
		this.op = op;
	}

	protected Junction(String op) {
		this.op = op;
	}

	public Junction add(Criterion criterion) {
		criteria.add(criterion);
		return this;
	}

	public String getOp() {
		return op;
	}

	public String toSqlString(QueryCriteria queryCriteria) {
		if (criteria.size() == 0)
			return "1=1";

		StringBuffer buffer = new StringBuffer().append('(');
		Iterator<Criterion> iter = criteria.iterator();
		while (iter.hasNext()) {
			buffer.append(iter.next().toSqlString(queryCriteria));
			if (iter.hasNext())
				buffer.append(' ').append(op).append(' ');
		}
		return buffer.append(')').toString();
	}

	@SuppressWarnings("deprecation")
	public List<Entry<String, Object>> getNamedValue(QueryCriteria queryCriteria) {

		List<Entry<String, Object>> namedValue = this.safeNamedValue(null);

		Iterator<Criterion> iter = criteria.iterator();
		while (iter.hasNext()) {
			namedValue.addAll(iter.next().getNamedValue(queryCriteria));
		}
		return namedValue;

	}

	public String toString() {
		return '(' + StringUtils.join(criteria.iterator(), ' ' + op + ' ') + ')';
	}

}
